<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright   Copyright (c) 2014 X.commerce, Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
/** @var $this \Magento\Eav\Block\Adminhtml\Attribute\Edit\Options\Options */
?>
<fieldset class="fieldset">
    <legend class="legend"><span><?php echo __('Manage Options (values of your attribute)') ?></span></legend>
    <div id="manage-options-panel">
        <table class="data-table" cellspacing="0">
            <thead>
                <tr id="attribute-options-table">
                    <th class="col-draggable"></th>
                    <th class="col-default"><?php echo __('Is Default') ?></th>
                    <?php
                    $storelist = $this->getStores();
                    foreach ($storelist as $_store):
                        ?>
                        <th><?php echo $_store->getName() ?></th>
                    <?php endforeach;
                    $storetotal = count($storelist) + 3;
                    ?>
                    <th class="col-delete">&nbsp;</th>
                </tr>
            </thead>
            <tbody data-role="options-container"></tbody>
            <tfoot>
                <th colspan="<?php echo $storetotal; ?>" class="col-actions-add">
                    <?php if (!$this->getReadOnly() && !$this->canManageOptionDefaultOnly()):?>
                        <button id="add_new_option_button" title="<?php echo __('Add Option'); ?>"
                            type="button" class="action- scalable add">
                             <span><?php echo __('Add Option'); ?></span>
                        </button>
                    <?php endif; ?>
                </th>
            </tfoot>
        </table>
        <input type="hidden" id="option-count-check" value="" />
    </div>
    <script id="row-template" type="text/x-jquery-tmpl">
         <tr>
            <td class="col-draggable">
                <?php if (!$this->getReadOnly() && !$this->canManageOptionDefaultOnly()): ?>
                    <div data-role="draggable-handle" class="draggable-handle" title="<?php echo __('Sort Option'); ?>"></div>
                <?php endif; ?>
                <input data-role="order" type="hidden" name="option[order][{{id}}]"  value="{{sort_order}}" <?php if ($this->getReadOnly() || $this->canManageOptionDefaultOnly()): ?> disabled="disabled"<?php endif; ?>/>
            </td>
            <td class="col-default">
                <input class="input-radio" type="{{intype}}" name="default[]" value="{{id}}" {{checked}}<?php if ($this->getReadOnly()):?>disabled="disabled"<?php endif;?>/>
            </td>
            <?php foreach ($this->getStores() as $_store): ?>
            <td class="col-{{id}}"><input name="option[value][{{id}}][<?php echo $_store->getId() ?>]" value="{{store<?php echo $_store->getId() ?>}}" class="input-text<?php if ($_store->getId() == \Magento\Store\Model\Store::DEFAULT_STORE_ID): ?> required-option<?php endif; ?>" type="text" <?php if ($this->getReadOnly() || $this->canManageOptionDefaultOnly()):?> disabled="disabled"<?php endif;?>/></td>
            <?php endforeach; ?>
            <td id="delete_button_container_{{id}}" class="col-delete">
                <input type="hidden" class="delete-flag" name="option[delete][{{id}}]" value="" />
                <?php if (!$this->getReadOnly() && !$this->canManageOptionDefaultOnly()):?>
                    <button title="<?php echo __('Delete') ?>" type="button"
                        class="action- scalable delete delete-option"
                        >
                        <span><?php echo __('Delete') ?></span>
                    </button>
                <?php endif;?>
            </td>
        </tr>
    </script>
    <script type="text/javascript">
require(['jquery', "jquery/ui"], function(jQuery){

    var optionDefaultInputType = 'radio';

    // IE removes quotes from element.innerHTML whenever it thinks they're not needed, which breaks html.
    var templateText = $('row-template').innerHTML;

    var attributeOption = {
        table: $('attribute-options-table'),
        templateSyntax: /(^|.|\r|\n)({{(\w+)}})/,
        templateText: templateText,
        itemCount: 0,
        totalItems: 0,
        isReadOnly: <?php echo (int)$this->getReadOnly(); ?>,
        add: function(data) {
            this.template = new Template(this.templateText, this.templateSyntax);
            var isNewOption = false;
            if (typeof data.id == 'undefined') {
                data = {
                    'id': 'option_' + this.itemCount,
                    'sort_order': this.itemCount + 1
                };
                isNewOption = true;
            }
            if (!data.intype) {
                data.intype = optionDefaultInputType;
            }

            Element.insert($$('[data-role=options-container]')[0], this.template.evaluate(data));
            if (isNewOption && !this.isReadOnly) {
                this.enableNewOptionDeleteButton(data.id);
            }
            this.bindRemoveButtons();
            this.itemCount++;
            this.totalItems++;
            this.updateItemsCountField();
        },
        remove: function(event) {
            var element = $(Event.findElement(event, 'tr')); // !!! Button already have table parent in safari
            // Safari workaround
            element.ancestors().each(function(parentItem) {
                if (parentItem.hasClassName('option-row')) {
                    element = parentItem;
                    throw $break;
                } else if (parentItem.hasClassName('box')) {
                    throw $break;
                }
            });

            if (element) {
                var elementFlags = element.getElementsByClassName('delete-flag');
                if (elementFlags[0]) {
                    elementFlags[0].value = 1;
                }

                element.addClassName('no-display');
                element.addClassName('template');
                element.hide();
                this.totalItems--;
                this.updateItemsCountField();
            }
        },
        updateItemsCountField: function() {
            $('option-count-check').value = this.totalItems > 0 ? '1' : '';
        },
        enableNewOptionDeleteButton: function(id) {
            $$('#delete_button_container_' + id + ' button').each(function(button) {
                button.enable();
                button.removeClassName('disabled');
            });
        },
        bindRemoveButtons: function() {
            var buttons = $$('.delete-option');
            for (var i = 0; i < buttons.length; i++) {
                if (!$(buttons[i]).binded) {
                    $(buttons[i]).binded = true;
                    Event.observe(buttons[i], 'click', this.remove.bind(this));
                }
            }
        }
    };

    attributeOption.bindRemoveButtons();

    if ($('add_new_option_button')) {
        Event.observe('add_new_option_button', 'click', attributeOption.add.bind(attributeOption));
    }
    <?php foreach ($this->getOptionValues() as $_value): ?>
    attributeOption.add(<?php echo $_value->toJson() ?>);
    <?php endforeach; ?>
    <?php if (!$this->getReadOnly() && !$this->canManageOptionDefaultOnly()):?>
    jQuery(function($) {
        $('[data-role=options-container]').sortable({
            distance: 8,
            tolerance: "pointer",
            cancel: 'input, button',
            axis: 'y',
            update: function() {
                $('[data-role=options-container] [data-role=order]').each(function(index, element) {
                    $(element).val(index + 1);
                });
            }
        });
    });
    <?php endif; ?>

    window.attributeOption = attributeOption;
    window.templateText = templateText;
    window.optionDefaultInputType = optionDefaultInputType;
    //]]>
    
});
</script>
</fieldset>
